<?php
namespace addon\cms\logic;
use app\common\logic\LogicBase;
use \tpfcore\util\Tree;
use tpfcore\Core;
use tpfcore\helpers\StringHelper;
use think\Db;
use \think\Config;

class PostsVideos extends LogicBase
{
	public function getPostsVideos($where=[]){
		return self::getList($where);
	}
	public function savePostsVideos($data){
		/* 验证文章 */
		$validate_posts=Core::addonValidate("Posts");
		$validate_result = $validate_posts->scene('add_posts_videos')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate_posts->getError(), null];
        }
        
        $last_id=Core::loadAddonModel("Posts")->saveObject($data);

        /* 处理老图片 */
        if(!empty($data['old_desc'])){
        	$old_data_videos =[];
        	foreach ($data['old_desc'] as $key => $value) {
        		$old_data_videos[]=['id'=>$key,"desc"=>$value,"video_source"=>$data['old_video_source'][$key]];
        	}
        	Core::loadAddonModel("PostsVideos")->saveAll($old_data_videos);
        	unset($data['old_desc']);
        }

        if($last_id){
        	/* 处理图片 */
	        if(!empty($data['url'])){

	        	$data_videos=[];

	        	foreach ($data['url'] as $key => $value) {

	        		if(empty($value)) continue;

	        		$data_videos[]=["posts_id"=>isset($data['id'])?$data['id']:$last_id,"url"=>$value,"desc"=>$data['desc'][$key],"video_source"=>$data['video_source'][$key]];
	        	}
	        	Core::loadAddonModel($this->name)->saveAll($data_videos);
	        }
	        return [RESULT_SUCCESS, '操作成功', url("cms/PostsVideos/index")];

        }else{
        	return [RESULT_ERROR, '操作失败', null];
        }
	}

	public function del_imgae($data){
		// 删除真实图片
		if(isset($data['id'])){
			$posts_images = self::getOneObject($data,"url");

			if($posts_images){
				if(!empty($posts_images['url']) && is_file(ROOT_PATH.$posts_images['url'])){
					@unlink(ROOT_PATH.$posts_images['url']);
				}

				//删除数据
				$result = self::deleteObject($data,true);

				if($result){
					return [0,"操作成功",url('cms/PostsVideos/index')];
				}
				return [40045,"操作失败"]; 
			}
			return [40045,"你删除的数据不存在"]; 
		}
		// 删除上传图片
		if(isset($data['url']) && is_file(ROOT_PATH.$data['url'])){
			@unlink(ROOT_PATH.$data['url']);
			return [0,"操作成功",url('cms/PostsVideos/index')];
		}
		return [40045,"操作失败"];
	}

	public function delPostsVideos($data){
		$listPostsVideos = $this->getPostsVideos(["where"=>["posts_id"=>$data['id']]]);

		if($listPostsVideos){
			//这里可把真实图片删除
			foreach ($listPostsVideos as $key => $value) {
				@unlink(ROOT_PATH.$value['url']);
			}
			if(!self::deleteObject(["posts_id"=>$data['id']],true)){
				return [RESULT_ERROR, '删除失败', url("cms/PostsVideos/index")];
			}
		}

		if(Core::loadAddonModel("Posts")->deleteObject(['id'=>$data['id']],true)){
			return [RESULT_SUCCESS, '删除成功', url("cms/PostsVideos/index")];	
		}else{
			return [RESULT_ERROR, '删除失败', url("cms/PostsVideos/index")];
		}
	}
	
}